package com.xywy.bloodandroid.adapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.xywy.bloodandroid.R;
import com.xywy.bloodandroid.base.BasicAdapter;
import com.xywy.bloodandroid.bean.PlusAsk;
import com.xywy.bloodandroid.bean.QuestionDeatail;
import com.xywy.bloodandroid.bean.QuestionReplay;
import com.xywy.bloodandroid.bean.User;
import com.xywy.bloodandroid.custom.MyListView;
import com.xywy.bloodandroid.receiver.BroadcastAction;
import com.xywy.bloodandroid.util.Constants;
import com.xywy.bloodandroid.util.ImageLoader.ImageCallback;
import com.xywy.bloodandroid.util.NetUtil;
import com.xywy.bloodandroid.util.UIUtil;
import com.xywy.bloodandroid.vollery.OnVolleyResponseListener;
import com.xywy.bloodandroid.vollery.PostRequest;
import com.xywy.bloodandroid.vollery.VolleyManager;

public class QuestionDetailAdapter extends BasicAdapter implements OnClickListener  {
	private List<QuestionDeatail> list;
	private LayoutInflater inflater;
	private DoctorQuestionRepalyAdapter adapter;
	private List<QuestionReplay> list2;
	private List<PlusAsk> list3;
	private int num;
	protected ProgressDialog waittingDialog;
	
	private String  art_id;
	private FrameLayout bottom_bar;
	private EditText text_input;
	private ImageView send_control;
	
	private InputMethodManager imm;

	public QuestionDetailAdapter(Context context, List<QuestionDeatail> list,String art_id,FrameLayout bottom_bar,EditText text_input,ImageView send_control,
			List<QuestionReplay> list2) {
		super(context, list);
		this.list2 = list2;
		this.list=list;
		this.context = context;
		this.inflater = LayoutInflater.from(context);
//		list2 = new ArrayList<QuestionReplay>();
		
        this.art_id=art_id;
        this.bottom_bar=bottom_bar;
        this.text_input=text_input;
        this.send_control=send_control;
        send_control.setOnClickListener(this);
    
        
        text_input.addTextChangedListener(mTextWatcher);
        text_input.setSelection(text_input.length());
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final viewholder holder;
		
		if (convertView == null) {
			
			holder = new viewholder();
			convertView = inflater.inflate(R.layout.item_question_detail, null);
			holder.title = (TextView) convertView.findViewById(R.id.title);
			holder.date = (TextView) convertView.findViewById(R.id.date);
			holder.remark = (TextView) convertView.findViewById(R.id.remark);
			holder.head = (ImageView) convertView.findViewById(R.id.head);
			holder.doctor_name = (TextView) convertView
					.findViewById(R.id.doctor_name);
			holder.doctor_honor = (TextView) convertView
					.findViewById(R.id.doctor_honor);
			holder.help_number = (TextView) convertView
					.findViewById(R.id.help_number);

			holder.ask_text = (TextView) convertView
					.findViewById(R.id.ask_text);

			holder.textview1 = (TextView) convertView
					.findViewById(R.id.textview1);
			holder.question_content = (TextView) convertView
					.findViewById(R.id.question_content);// 问题分析

			holder.question_sugges = (TextView) convertView
					.findViewById(R.id.question_suggest);// 意见建议

			holder.xian1 = convertView.findViewById(R.id.xian1);
			holder.xian2 = convertView.findViewById(R.id.xian2);
			holder.listView = (MyListView) convertView
					.findViewById(R.id.mylistview);

			holder.star1 = (ImageView) convertView.findViewById(R.id.star1);
			holder.star2 = (ImageView) convertView.findViewById(R.id.star2);
			holder.star3 = (ImageView) convertView.findViewById(R.id.star3);
			holder.star4 = (ImageView) convertView.findViewById(R.id.star4);
			holder.star5 = (ImageView) convertView.findViewById(R.id.star5);
			holder.submit_text = (TextView) convertView
					.findViewById(R.id.submit_text);
			convertView.setTag(holder);
		} else {
			holder = (viewholder) convertView.getTag();
		}
		
		System.out.println("获取我的值是否正确呢 额度的   ........"+list.size());
		if(list3!=null)
		list3.clear();
	    list3=new ArrayList<PlusAsk>();
	    if(list2 != null && list2.size()>list.size()){
	    	if(list2.get(position).getPlusAskList()!=null)
	    		list3.addAll(list2.get(position).getPlusAskList());
	    	if(list3.size()>0){
	    		adapter = new DoctorQuestionRepalyAdapter(context, list3);
	    		holder.listView.setAdapter(adapter);
	    	}
	    }
		
		
		
		
	    
		String title = list.get(0).getTitle();
		String date = list.get(0).getAskTime();
		String reamrk = list.get(0).getState();
		holder.title.setText(title);
		holder.date.setText(date);

//		String doctor_replay = list.get(position).getRepliedlist();
//		list2.addAll((List<QuestionReplay>) JsonUtil.parseJsonToList(
//				doctor_replay, new TypeToken<List<QuestionReplay>>() {
//				}.getType()));
        if(list2 != null && list2.size()>0){
        	String head = list2.get(position).getDocAvatar();
        	Drawable cachedImage = loader.loadDrawable(head, holder.head,
        			new ImageCallback() {
        		
        		@Override
        		public void imageLoaded(Drawable imageDrawable,
        				ImageView imageView, String imageUrl) {
        			if (imageView != null && imageDrawable != null) {
        				imageView.setBackgroundDrawable(imageDrawable);
        			}
        		}
        	});
        	String doctor_name = list2.get(position).getDocName();
        	String doctor_honor = list2.get(position).getDocLevel();
        	String help_number = "已帮助用户：" + list2.get(position).getDnum();
        	if (cachedImage == null) {
        		holder.head.setBackgroundResource(R.drawable.head);
        	} else {
        		holder.head.setBackgroundDrawable(cachedImage);
        	}
        	holder.doctor_name.setText(doctor_name);
        	holder.doctor_honor.setText(doctor_honor);
        	holder.help_number.setText(help_number);
        }
        



		if (list3.size() <=0) {
			holder.xian1.setVisibility(View.GONE);
			holder.xian2.setVisibility(View.GONE);
		} else {
			holder.xian1.setVisibility(View.VISIBLE);
			holder.xian2.setVisibility(View.VISIBLE);
		}

		if ("0".equals(reamrk)) {
			holder.remark.setText("未回复");
		} else {
			holder.remark.setText("已回复");
		}
        if(list2!= null && list2.size()>list.size()){
        	// 问题分析 和指导意见在一起
        	String replay_content = list2.get(position).getDocRepliedContent();
        	String[] content = replay_content.split("\\*\\*\\**\\*");
        	if (content.length < 2 && content.length > 5) {
        		holder.textview1.setVisibility(View.GONE);
        		holder.question_content.setVisibility(View.GONE);
        		if(content[0].length()>5)
        			holder.question_sugges.setText(content[0].substring(5));
        	} else if (content.length >= 2) {
        		holder.textview1.setVisibility(View.VISIBLE);
        		holder.question_content.setVisibility(View.VISIBLE);
        		holder.question_content.setText(content[0].substring(5));
        		holder.question_sugges.setText(content[1].substring(5));
        		
        	}
        	String grade1 = list2.get(position).getGrade();
        	double grade=Double.valueOf(grade1);
        	if (grade == 0) {
        		
        	} else if (grade == 1) {
        		holder.star1.setImageResource(R.drawable.entiny_star);
        	} else if (grade == 2) {
        		holder.star1.setImageResource(R.drawable.entiny_star);
        		holder.star2.setImageResource(R.drawable.entiny_star);
        	} else if (grade == 3) {
        		holder.star1.setImageResource(R.drawable.entiny_star);
        		holder.star2.setImageResource(R.drawable.entiny_star);
        		holder.star3.setImageResource(R.drawable.entiny_star);
        	} else if (grade == 4) {
        		holder.star1.setImageResource(R.drawable.entiny_star);
        		holder.star2.setImageResource(R.drawable.entiny_star);
        		holder.star3.setImageResource(R.drawable.entiny_star);
        		holder.star4.setImageResource(R.drawable.entiny_star);
        	} else if (grade == 5) {
        		holder.star1.setImageResource(R.drawable.entiny_star);
        		holder.star2.setImageResource(R.drawable.entiny_star);
        		holder.star3.setImageResource(R.drawable.entiny_star);
        		holder.star4.setImageResource(R.drawable.entiny_star);
        		holder.star5.setImageResource(R.drawable.entiny_star);
        	}
        }

		
		
		
		

		
		holder.star1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				System.out.println("到底是什么呢 ...||" + (flag1 % 2 != 0));
				if (flag1 % 2 == 0) {
					holder.star1.setBackgroundResource(R.drawable.empty_star);
					num--;
					flag1--;
				} else {
					holder.star1.setBackgroundResource(R.drawable.entiny_star);
					num++;
					flag1++;
				}
			}
		});
		holder.star2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (flag2 % 2 == 0) {
					holder.star2.setBackgroundResource(R.drawable.empty_star);
					num--;
					flag2--;
				} else {
					holder.star2.setBackgroundResource(R.drawable.entiny_star);
					num++;
					flag2++;
				}
			}
		});

		holder.star3.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (flag3 % 2 == 0) {
					holder.star3.setBackgroundResource(R.drawable.empty_star);
					num--;
					flag3--;
				} else {
					holder.star3.setBackgroundResource(R.drawable.entiny_star);
					num++;
					flag3++;
				}
			}
		});
		holder.star4.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (flag4 % 2 == 0) {
					holder.star4.setBackgroundResource(R.drawable.empty_star);
					num--;
					flag4--;
				} else {
					holder.star4.setBackgroundResource(R.drawable.entiny_star);
					num++;
					flag4++;
				}
			}
		});
		holder.star5.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (flag5 % 2 == 0) {
					holder.star5.setBackgroundResource(R.drawable.empty_star);
					num--;
					flag5--;
				} else {
					holder.star5.setBackgroundResource(R.drawable.entiny_star);
					num++;
					flag5++;
				}
			}
		});
		if(list2 != null && list2.size()>=list.size()){
			rid = list2.get(position).getDocConversionId();
			doctor_id = list2.get(position).getDoc_id();
			
			holder.submit_text.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					System.out.println("打印一下..."+num); 
					SendDoctorRemark(art_id,doctor_id,rid,null);
					
				}
			});
			
			holder.ask_text.setOnClickListener(new OnClickListener() {
				
				
				
				@Override
				public void onClick(View v) {
					bottom_bar.setVisibility(View.VISIBLE);
					text_input.requestFocus();
					imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);  
					imm.showSoftInput(text_input, 0);  
				}
			});
		}
		return convertView;
	}

	private class viewholder {
		private TextView title;
		private TextView date;
		private TextView remark;
		private ImageView head;
		private TextView doctor_name;
		private TextView doctor_honor;
		private TextView help_number;

		private TextView ask_text;// 追问

		private TextView textview1;// "问题分析"的字
		private TextView question_content;// 问题分析
		private TextView question_sugges;// 意见建议
		private View xian1;
		private View xian2;

		private MyListView listView;

		private ImageView star1;
		private ImageView star2;
		private ImageView star3;
		private ImageView star4;
		private ImageView star5;
		private TextView submit_text;// 提交评价按钮
	}

	private int flag1 = 1;
	private int flag2 = 1;
	private int flag3 = 1;
	private int flag4 = 1;
	private int flag5 = 1;

	private String rid;
	private String doctor_id;


	private void SendDoctorRemark(String  art_id,String doctor_id,String rid,String gcons) {
		PostRequest<String> postRequest =new PostRequest<String>(Constants.getUrl("club", "Club_Appraisal"), String.class, new OnVolleyResponseListener<String>() {

			@Override
			public void onError(VolleyError volleyError) {
				UIUtil.DissDialog(context, waittingDialog);
				UIUtil.showToast(context, context.getString(R.string.network_slow));
			}

			@Override
			public void onSuccess(String response) {
				UIUtil.DissDialog(context, waittingDialog);
				
				JSONObject object;
				try {
					object = new JSONObject(response);
					int  state=object.optInt("state");
					String error=object.optString("error");
					if(state==10000){
						UIUtil.showToast(context, "评价成功");
					}else{
						System.out.println("错误是.."+error);
						UIUtil.showToast(context, error);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("art_id", art_id);
		params.put("userid", User.getInstance(context).getUserid()); 
		
		params.put("rid", rid);
		params.put("doc_id", doctor_id);
		
		params.put("grade", num+"");
		if(gcons!=null)
		params.put("gcons", gcons);
		postRequest.setParams(params);
		postRequest.setIsParseJson(false);
		if (NetUtil.hasNetwork(context)) {
			waitingDialog(context, context.getString(R.string._remark_comit));
			VolleyManager.addRequest(postRequest, context);
			
		} else {
			UIUtil.showToast(context, context.getResources().getString(R.string.network_slow));
			UIUtil.DissDialog(context, waittingDialog);
		
		}
	}
	
	public void waitingDialog(Context context, String message) {
		if (waittingDialog == null)
			waittingDialog = new ProgressDialog(context);
		waittingDialog.setCanceledOnTouchOutside(false);//
		waittingDialog.setMessage(message);
		waittingDialog.show();
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.send_control:
			String contentss=text_input.getText().toString().trim();
			System.out.println("获取的内容||"+contentss);
			if(contentss.length()>0){
				getAskQuestion(contentss);
			}else{
				UIUtil.showToast(context, "追问内容不能为空~");
			}
			
			break;

		default:
			break;
		}
		
	}
     /**
      * 追问问题
      */
	private void getAskQuestion(String contentss) {
		PostRequest<String> postRequest=new PostRequest<String>(Constants.getUrl("club", "Club_zhuiWen"), String.class, new OnVolleyResponseListener<String>() {

			@Override
			public void onError(VolleyError volleyError) {
				UIUtil.DissDialog(context, waittingDialog);
				UIUtil.showToast(context, context.getString(R.string.network_slow));
			}

			@Override
			public void onSuccess(String response) {
				UIUtil.DissDialog(context, waittingDialog);
				JSONObject object;
				try {
					object = new JSONObject(response);
					int  state=object.optInt("state");
					String error=object.optString("error");
					System.out.println("追问成功的错误是.."+error);
					if(state==200){
//						InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
//						imm.hideSoftInputFromInputMethod(text_input.getWindowToken(), 0);
//						bottom_bar.setVisibility(View.GONE);
						UIUtil.showToast(context, "追问成功");
						Intent intent=new Intent(BroadcastAction.ACTION_HIDE_SOFT_AND_REFESH_VIEWS);
						context.sendBroadcast(intent);
					
						
					}else{
						UIUtil.showToast(context, error);
					}
				
			}catch (JSONException e) {
				e.printStackTrace();
			}
				}
		});
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("art_id", art_id);
		params.put("userid", User.getInstance(context).getUserid()); 
		params.put("conversionId", rid);
		params.put("doc_id", doctor_id);
		params.put("detail", contentss);
		
		postRequest.setParams(params);
		postRequest.setIsParseJson(false);
		if (NetUtil.hasNetwork(context)) {
			waitingDialog(context, context.getString(R.string._remark_comit));
			VolleyManager.addRequest(postRequest, context);
			
		} else {
			UIUtil.showToast(context, context.getResources().getString(R.string.network_slow));
			UIUtil.DissDialog(context, waittingDialog);
		
		}
		
	}
	

	/**
	 * 每个字是两个字符
	 * 
	 * @param c
	 * @return
	 */
	private long calculateLength(CharSequence c) {
		double len = 0;
		for (int i = 0; i < c.length(); i++) {
			int tmp = (int) c.charAt(i);
			if (tmp > 0 && tmp < 127) {
				len += 0.5;
			} else {
				len++;
			}
		}
		return Math.round(len);
	}


	private static final int MAX_COUNT = 50;

	private TextWatcher mTextWatcher = new TextWatcher() {
		private int editStart;
		private int editEnd;

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {

		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {

		}

		@Override
		public void afterTextChanged(Editable s) {
			editStart = text_input.getSelectionStart();
			editEnd = text_input.getSelectionEnd();
			text_input.removeTextChangedListener(mTextWatcher);
			while (calculateLength(s.toString()) > MAX_COUNT) {
				s.delete(editStart - 1, editEnd);
				editStart--;
				editEnd--;
			}
			text_input.addTextChangedListener(mTextWatcher);
//			setLeftCount();
		}
	};
	
	

}
